package com.team.game.Game.Wizards.FireWizard;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;

import com.team.game.Game.Impacts;
import com.team.game.Game.Levels;
import com.team.game.framework.Abstract.GesturesInfo;
import com.team.game.framework.Abstract.Spell;
import com.team.game.framework.Game;
import com.team.game.framework.impl.MainActivity;
import com.team.game.framework.impl.Scale_X_Y;
import com.team.game.framework.impl.SurfaceThread;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import static com.team.game.Screens.Upgrade_Screen.rect_PictureFrame;

public class Fire_Ball extends Spell {

    private PointF pointF = new PointF(0, 0);
    private Matrix FireBallMatrix = new Matrix();
    private ArrayList<Bitmap> FireBall;
    private Bitmap FireBallBoom;
    private boolean Boom = false;
    private int BoomCounter;
    private float AddX;
    private float AddY;
    private Path path = new Path();
    private PathMeasure pathMeasure;
    private float Damage;
    private RectF CurrentRect = new RectF();
    private Rect RectSource = new Rect();
    private RectF StartRect = new RectF();
    private float speed = 45;
    private float Radius;
    private float a = 0; //kut
    private int AnimationCounter = 0;


    private float frame = 0;
    private float Lenght;
    private float Speed ;
    private RectF FingerRect;
    private Bitmap Finger;
    private boolean TrueFinger = false;
    private Matrix matrix;
    private float  X_Destenation, Y_Destenation;


    private boolean if_Upgrade = false;
    private RectF PictureFrame;
    public Fire_Ball () {
        super ();

        if_Upgrade = true;
        WaitForTap = false;

        PictureFrame = rect_PictureFrame; // рамка

        pointF.set(650*Scale_X_Y.scale,800*Scale_X_Y.scale); // точка к которой летим

        X_Destenation = 95 * Scale_X_Y.scale;//рука
        Y_Destenation = 107 * Scale_X_Y.scale;


        matrix = new Matrix();
        FingerRect = new RectF(); // рука

        path.moveTo(700*Scale_X_Y.scale, 1100*Scale_X_Y.scale); // стрелка
        path.lineTo(700*Scale_X_Y.scale, 800*Scale_X_Y.scale);
        path.moveTo(600*Scale_X_Y.scale, 900*Scale_X_Y.scale);
        path.lineTo(700*Scale_X_Y.scale, 800*Scale_X_Y.scale);
        path.lineTo(800*Scale_X_Y.scale, 900*Scale_X_Y.scale);


        Lenght = 683*Scale_X_Y.scale;  //длинна отрезка
        Speed = 1 * Scale_X_Y.scale;


        InputStream inputStream;
        try {
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/hero_1/spell_1.png");
            icon_spell = BitmapFactory.decodeStream (inputStream);
            inputStream = MainActivity.manager.open ("Picture/Upgrade_Screen/Finger.png");
            Finger = BitmapFactory.decodeStream (inputStream);
        } catch (IOException e) {
            e.printStackTrace ();
        }


        // начальный рект для шара
        StartRect.set(PictureFrame.right-((PictureFrame.right-PictureFrame.left)/2)-FireBall.get(0).getWidth()/2,
                 PictureFrame.bottom ,
                PictureFrame.right-((PictureFrame.right-PictureFrame.left)/2)+FireBall.get(0).getWidth()/2 ,
                PictureFrame.bottom+FireBall.get(0).getWidth()/2);

        CurrentRect = StartRect;


        FireBallMatrix.postScale(Scale_X_Y.Scale_X, Scale_X_Y.Scale_Y); // уберется в будущем
        FireBallMatrix.postTranslate(CurrentRect.left, CurrentRect.top);


        cost = new int[]{10, 20, 30, 40};
    }
    public void cut(Rect rect, RectF currentRect, RectF startRect)
    {
        if( currentRect.left < startRect.left ) {
            rect.left = (int)( startRect.left - currentRect.left );
            currentRect.left = startRect.left;
        }
        else
            rect.left = 0;
        if( currentRect.right > startRect.right ) {
            rect.right = (int)( startRect.right - currentRect.left );
            currentRect.right = startRect.right;
        }
        else
            rect.right = FireBall.get(1).getWidth();
        if( currentRect.top < startRect.top )
        {
            rect.top = (int)( startRect.top - currentRect.top);
            currentRect.top = startRect.top;
        }
        else
            rect.top = 0;
        if( currentRect.bottom > startRect.bottom )
        {
            rect.bottom = (int)(startRect.bottom - currentRect.top);
            currentRect.bottom = startRect.bottom;
        }
        else
            rect.bottom = FireBall.get(1).getWidth();
    }
    @Override
    public void drowProfileExample (Canvas canvas, int level) {
        if(TrueFinger) {
            canvas.drawBitmap(Finger, null,FingerRect,null);
        }
        else{
            if (!Boom) {
                canvas.drawBitmap(FireBall.get(AnimationCounter), FireBallMatrix, null);
            } else
                canvas.drawBitmap(FireBallBoom, RectSource, CurrentRect, null);
        }
    }

    @Override
    public void updateProfileExample() {
//        //делим путь на небольшие сегменты
//        if(!TrueFinger) {
//            pathMeasure.getMatrix(speed * frame, matrix, PathMeasure.POSITION_MATRIX_FLAG);
//
//            //переводим матрицу в рект
//            matrix.mapRect(FingerRect);
//            FingerRect.bottom += Y_Destenation;
//            FingerRect.right += X_Destenation;
//            frame += 187.5 * SurfaceThread.deltaTime;
//            if(frame*Speed >= Lenght)
//                TrueFinger=true;
//        }
//        else {
//            this.updateSpell();
//        }
    }

    @Override
    public void setStartConfiguration() {

    }

    public Fire_Ball(Game game, RectF rectF) {
        super (game);

        // нужно делать в каждом скиле, устанавливаем посицию кружка перезагрузки, вершину ( она будет меняться) и время перезагрузки
        ProgressBarRect.set(19 * Scale_X_Y.scale, 55 * Scale_X_Y.scale, 69 * Scale_X_Y.scale, 105 * Scale_X_Y.scale);
        RectDstForBlackProgress.set(21 * Scale_X_Y.scale, 57 * Scale_X_Y.scale, 67 * Scale_X_Y.scale, 103 * Scale_X_Y.scale);
        TopOfRectProgressDst = RectDstForBlackProgress.top;
        TimeRecharch = 3;

        Damage = 100;
        Radius = 216 * Scale_X_Y.scale;
        StartRect.set(rectF);
        CurrentRect.right = rectF.right;
        CurrentRect.bottom = rectF.bottom;
        CurrentRect.left = rectF.right - FireBall.get(0).getWidth() * Scale_X_Y.Scale_X;
        CurrentRect.top = rectF.bottom - FireBall.get(0).getWidth() * Scale_X_Y.Scale_X;
        FireBallMatrix.postScale(Scale_X_Y.Scale_X, Scale_X_Y.Scale_Y);
        FireBallMatrix.postTranslate(CurrentRect.left, CurrentRect.top);
        RectSource.set(0, 0, 96, 96);


    }


    @Override
    public boolean updateSpell() {
        if (!WaitForTap) {

            double distance;

            float difX = pointF.x - CurrentRect.centerX();
            float difY = pointF.y - CurrentRect.centerY();

            distance = Math.sqrt(Math.pow((difX), 2.0) + Math.pow(difY, 2.0));
            float scale;
            if ((scale = (float) distance / speed * (float) (187.5 * SurfaceThread.deltaTime)) > 1) {
//             a=  (float)Math.sin((Math.sqrt (Math.pow (difY, 2.0)))/distance);
//             a = (float)Math.toDegrees(Math.asin(a));
                a = (float) ((Math.asin(difX / distance)) / (Math.PI)) * 180;

                AddX = ((difX) / scale);
                AddY = ((difY) / scale);

                CurrentRect.right += AddX;
                CurrentRect.left += AddX;
                CurrentRect.bottom += AddY;
                CurrentRect.top += AddY;
                //если делать только одно преобразование - нужно использовать сет
                //если их несколько - пре и пост
                //на форумах пишут что лучше пост
                FireBallMatrix.reset();
                FireBallMatrix.postScale(Scale_X_Y.Scale_X, Scale_X_Y.Scale_Y);
                FireBallMatrix.postRotate(a, FireBall.get(0).getWidth() / 2, FireBall.get(0).getWidth() / 2);
                FireBallMatrix.postTranslate(CurrentRect.left, CurrentRect.top);
                //if (time > 0.016) {
                // time = 0;
                AnimationCounter++;
                if (AnimationCounter > 11)
                    AnimationCounter = 0;
            } else {
                if (BoomCounter == 0) {
                    Boom = true;
                    CurrentRect.left = pointF.x - FireBallBoom.getHeight() * Scale_X_Y.scale / 2;
                    CurrentRect.right = pointF.x + FireBallBoom.getHeight() * Scale_X_Y.scale / 2;
                    CurrentRect.top = pointF.y - FireBallBoom.getHeight() * Scale_X_Y.scale / 2;
                    CurrentRect.bottom = pointF.y + FireBallBoom.getHeight() * Scale_X_Y.scale / 2;
                } else if (BoomCounter == 7) {
                    if(if_Upgrade) {
                        //game.getCurrentScreen().getLevel().impactOnTheRadius(pointF, Damage, Radius);
                        Impacts.impactOnTheRadius(level, pointF, Damage, Radius);
                    }
                }
                if (BoomCounter <= 18) {
                    RectSource.set(216 * BoomCounter, 0, 216 + 216 * BoomCounter, 216);
                    BoomCounter++;
                }

            }
            time += SurfaceThread.deltaTime; // cчитаем время
            if (time > 3) {
                this.restart();
                return false;
            }
            return true;
        }
        return true;


    }

    @Override
    public boolean activeSpell(GesturesInfo gesturesInfo1) {
        Active = true;
        level = (Levels) game.getCurrentScreen ().getLevel ();
        return true;  //wait for tap
    }

    @Override
    public boolean setMotionEventSpell(MotionEvent motionEvent) {
        pointF.set(motionEvent.getX(), motionEvent.getY());
        return WaitForTap = false; // если false то мы перестаем ожидать касание, и дальше обрабатываем жесты
    }

    @Override
    public void drawSpell(Canvas canvas) {
        if (!WaitForTap) {
            if (!Boom) {
                canvas.drawBitmap(FireBall.get(AnimationCounter), FireBallMatrix, null);
            } else
                canvas.drawBitmap(FireBallBoom, RectSource, CurrentRect, null);
        }
    }

    @Override
    public void restart() {
        if(!if_Upgrade) {
            this.progressBarRestart();
            WaitForTap = true;
            CurrentRect.right = StartRect.right;
            CurrentRect.bottom = StartRect.bottom;
            CurrentRect.left = StartRect.right - FireBall.get(0).getWidth() * Scale_X_Y.Scale_X;
            CurrentRect.top = StartRect.bottom - FireBall.get(0).getWidth() * Scale_X_Y.Scale_X;
        }
        else {
            TrueFinger = true;
            CurrentRect = StartRect;
        }
        AnimationCounter = 0;

        BoomCounter = 0;
        Boom = false;
        FireBallMatrix.reset();
        FireBallMatrix.postScale(Scale_X_Y.Scale_X, Scale_X_Y.Scale_Y);
        FireBallMatrix.postTranslate(CurrentRect.left, CurrentRect.top);
        RectSource.set(0, 0, 216, 216);
    }

    @Override
    public void dispose() {
        for (int i = 0; i < 6; i++)
            FireBall.get(i).recycle();
        FireBall.clear();
    }

    @Override
    public void setImages () {

        FireBall = new ArrayList<> (12);

        InputStream inputStream;
        try {
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/1.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/2.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/3.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/4.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/5.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/6.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/7.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/8.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/9.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/10.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/11.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));
            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/12.png");
            FireBall.add (BitmapFactory.decodeStream (inputStream));

            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/Fire_Ball_Normal.png");
            ProgressBarNormal = (BitmapFactory.decodeStream (inputStream));

            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/Fire_Ball_Active.png");
            ProgressBarActive = (BitmapFactory.decodeStream (inputStream));

            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/Fire_Ball_Radioactive.png");
            ProgressBarRActive = (BitmapFactory.decodeStream (inputStream));

            inputStream = MainActivity.manager.open ("Picture/Gestures/FireMage/FireBall/FireBallBoom.png");
            FireBallBoom = (BitmapFactory.decodeStream (inputStream));

        } catch (IOException e) {
            e.printStackTrace ();
        }

        SPELL_NAME = "fire_ball";
    }
}
